package p.ithorns.tools.excel.convert;

import cn.idev.excel.converters.Converter;
import cn.idev.excel.enums.CellDataTypeEnum;
import cn.idev.excel.metadata.GlobalConfiguration;
import cn.idev.excel.metadata.data.ReadCellData;
import cn.idev.excel.metadata.data.WriteCellData;
import cn.idev.excel.metadata.property.ExcelContentProperty;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * LocalDateStringConverter
 * <p>
 * EasyExcel String转LocalDate
 *
 * @author HtL
 * @date 2024/7/16 16:37
 * @since 1.0.0
 */
public class LocalDateConverter implements Converter<LocalDate> {

    /**
     * 日期格式
     */
    private final static DateTimeFormatter DATE_PATTERN = DateTimeFormatter.ofPattern("yyyy-MM-dd");


    @Override
    public Class<?> supportJavaTypeKey() {
        return LocalDate.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public LocalDate convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        CellDataTypeEnum type = cellData.getType();
        if (type.equals(CellDataTypeEnum.NUMBER)) {
            // Date javaDate = DateUtil.getJavaDate(cellData.getNumberValue().doubleValue());
            LocalDate localDate = LocalDate.of(1900, 1, 1);
            return localDate.plusDays(cellData.getNumberValue().longValue() - 2);
        }

        if (type.equals(CellDataTypeEnum.STRING)) {
            return LocalDate.parse(cellData.getStringValue(), DATE_PATTERN);
        }

        throw new UnsupportedOperationException("未知日期格式内容.");
    }

    @Override
    public WriteCellData<?> convertToExcelData(LocalDate value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        String datetime = DATE_PATTERN.format(value);
        return new WriteCellData<>(datetime);
    }

}